package com.das.mechanic_base.widget;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.processnew.ProcessNameHistoryAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3MyApp;
import com.das.mechanic_base.bean.process.ProcessName;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3EdittextWatcher;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.kproduce.roundcorners.RoundTextView;
import com.kproduce.roundcorners.RoundView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import razerdp.basepopup.BasePopupWindow;
import razerdp.util.animation.AlphaConfig;
import razerdp.util.animation.AnimationHelper;

//输入工序名称
public class X3BottomInputProcessNameDialog extends BasePopupWindow implements View.OnClickListener, ProcessNameHistoryAdapter.ItemClickListener {

    private LinearLayout ll_top;
    private RoundView v_top;
    private EditText et_input;
    private TextView tv_tips;
    private RoundTextView rv_affirm;
    private RoundTextView rv_cancel;
    private X3SwipeBackLayout sl_view;
    RecyclerView rlv_result;

    List<String> mTags = null;

    String userKey;

    String oldName;
    boolean isModify;
    int modifyIndex;
    private Handler mHandler;
    ProcessNameHistoryAdapter historyAdapter;

    public X3BottomInputProcessNameDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    public View onCreateContentView() {
        return createPopupById(R.layout.x3_bottom_process_name_dialog);
    }

    @Override
    public void onViewCreated(@NonNull View contentView) {
        super.onViewCreated(contentView);
        mHandler = new android.os.Handler();
        userKey =  SpHelper.getData("mobile","") + "_process_name";
        initTags();
        ll_top = findViewById(R.id.ll_top);
        v_top = findViewById(R.id.v_top);
        et_input = findViewById(R.id.et_input);
        sl_view = findViewById(R.id.sl_view);
        rv_affirm = findViewById(R.id.rv_affirm);
        rv_cancel = findViewById(R.id.rv_cancel);
        tv_tips = findViewById(R.id.tv_tips);
        rlv_result = findViewById(R.id.rlv_result);

        rv_affirm.setOnClickListener(this);
        rv_cancel.setOnClickListener(this);

        historyVisiable();

        et_input.addTextChangedListener(new X3EdittextWatcher() {
            @Override
            protected void textInputAfter(String content) {
                if (content.length()>=50){
                    tv_tips.setVisibility(View.VISIBLE);
                }else{
                    tv_tips.setVisibility(View.GONE);
                }
            }
        });

        sl_view.setIsBackToEnd(false);
        sl_view.setSwipeBackListener(new X3SwipeBackLayout.OnSwipeBackListener() {
            @Override
            public void onViewPositionChanged(View mView, float swipeBackFraction, float swipeBackFactor) {
                if (swipeBackFraction >= 0.5) {
                    onViewSwipeFinished(mView,true);
                }
            }

            @Override
            public void onViewSwipeFinished(View mView, boolean isEnd) {
                if (isEnd) {
                    dismiss();
                }
            }

            @Override
            public void onViewBack() {
                // 下拉弹回
            }
        });

        rlv_result.setLayoutManager(ChipsLayoutManager.newBuilder(getContext())
                .setOrientation(ChipsLayoutManager.HORIZONTAL)
                .setMaxViewsInRow(8)
                .build());

        historyAdapter = new ProcessNameHistoryAdapter(getContext());
        historyAdapter.setItemClickListener(this);
        rlv_result.setAdapter(historyAdapter);
        historyAdapter.changeSearch(mTags);
    }

    private void initTags(){
        ProcessName processName = (ProcessName) SpHelper.getProcessName(userKey);
        if (processName!=null){
            mTags = processName.names;
            if (mTags!=null){
                Collections.reverse(mTags);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rv_cancel) {
            dismiss();
        } else if (id == R.id.rv_affirm) {
            String tag = et_input.getText().toString().trim();
            selectedTag(tag);
        }
    }

    private void selectedTag(String tag){
        if (X3StringUtils.isEmpty(tag)) {
            X3ToastUtils.showMessage(getContext().getString(R.string.x3_no_input_trim));
            return;
        }
        ProcessName processName =  SpHelper.getProcessName(userKey);
        if (processName == null) {
            processName = new ProcessName();
        }
        List<String> names = processName.names;
        if (names == null) {
            names = new ArrayList<>();
            names.add(tag);
        } else {
            if (names.contains(tag)){
                names.remove(tag);
            }
            if (names.size() >= 10) {
                names.add(tag);
                names = names.subList(1,11);
            } else {
                names.add(tag);
            }
        }
        processName.names = names;
        SpHelper.saveData(userKey, processName);
        dismiss();
        if (iOnClickOk != null){
            if (isModify){
                iOnClickOk.iOnClickOk(tag,modifyIndex);
            } else {
                iOnClickOk.iOnClickOk(tag);
            }
        }
    }

    private void historyVisiable(){
        if (mTags != null && mTags.size()>0){
            rlv_result.setVisibility(View.VISIBLE);
        } else {
            rlv_result.setVisibility(View.GONE);
        }
    }

    IOnClickOk iOnClickOk;

    public void setIOnClickOk(IOnClickOk iOnClickOk) {
        this.iOnClickOk = iOnClickOk;
    }

    @Override
    public void itemClick(String text) {
        selectedTag(text);
    }

    public interface IOnClickOk{
        void iOnClickOk(String content );
        void iOnClickOk(String content,int index);
    }

    @Override
    public void showPopupWindow() {
        super.showPopupWindow();
        et_input.setFocusable(true);
        et_input.setFocusableInTouchMode(true);
        et_input.requestFocus();

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) et_input.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(et_input, 0);
            }
        },300);

    }

    @Override
    protected Animation onCreateShowAnimation() {
        return AnimationHelper.asAnimation()
                .withAlpha(AlphaConfig.IN.duration(0))
                .toShow();
    }

    @Override
    public void dismiss() {
        X3StringUtils.hideSoftInput(et_input);
        super.dismiss();
    }

    @Override
    protected Animation onCreateDismissAnimation() {
        return AnimationHelper.asAnimation()
                .withAlpha(AlphaConfig.OUT.duration(0))
                .toDismiss();
    }

    public String getOldName() {
        return oldName;
    }

    public void setOldName(String oldName) {
        this.oldName = oldName;
        if (!TextUtils.isEmpty(oldName)){
            et_input.setText(oldName);
        }
    }

    public boolean isModify() {
        return isModify;
    }

    public void setModify(boolean modify) {
        isModify = modify;
    }

    public int getModifyIndex() {
        return modifyIndex;
    }

    public void setModifyIndex(int modifyIndex) {
        this.modifyIndex = modifyIndex;
    }
}
